//
//  LDWorthVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/5/20.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit

class LDWorthVC: UIViewController {
    
    var headImgView:UIImageView?
    var contentView:UICollectionView?
    var cellid = "collectioncell"
    var headid = "collectionhead"
    var tapcellid = "collectiontap"
    
    var titleArr = ["人才认证","兼职","就业保险","叮咚体验站"]
    var imgNameUrlArr = ["人才认证","兼职","就业保险","叮咚体验站"]
    var h5Arr = [String]()
    
    var headH:CGFloat = IPHONE6UP ? 240:220
    var model:LDWorthConfigureModel? = nil
    
    var oldData = NSArray()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setDefaultContent()
        //        bk_performBlock({ [weak self] (obj) in
        //
        //            self?.cleanCache()
        //            self?.requestNet()
        //        }, onQueue: dispatch_get_main_queue(), afterDelay: NSTimeInterval.init(3))
        
        
        //        bk_performBlock({ [weak self] (obj) in
        //
        //        requestNet()
        //        }
        //        requestNet()
        
        //        rdv_tabBarController.setTabBarHidden(false, animated: true)
        
        //        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(0))
        //        navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: UIBarMetrics.Default)
        //        navigationController?.navigationBar.shadowImage = UIImage()
    }
    //
    override func viewWillAppear(animated: Bool) {
        
        requestNet()
        requestNew()
        //        navigationController?.navigationBar.translucent = true
        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(0))
        navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: UIBarMetrics.Default)
        navigationController?.navigationBar.shadowImage = UIImage()
        //        navigationController?.navigationBar.barTintColor = LDGolbalColor.Green
        
    }
    
    override func viewDidAppear(animated: Bool) {
        
        navigationController?.navigationBar.translucent = true
        rdv_tabBarController.setTabBarHidden(false, animated: true)
    }
    
    func requestNew() {
        
        //
        var newData = NSArray()
        LDCheckPublicInfo.shareInstance.queryWorthContent(false, succ: {[weak self] (value) in
            
            newData = NSArray.init(array: value)
            
            if newData.isEqualToArray(self?.oldData as! [AnyObject]) == true {
                
                return
            } else {
                
                self?.updateUI(value)
            }
            
            }, fail: nil)
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        navigationController?.navigationBar.translucent = false
        let image = UIImage.setImageWithColor(LDGolbalColor.Green.colorWithAlphaComponent(1))
        self.navigationController?.navigationBar.setBackgroundImage(image, forBarMetrics: UIBarMetrics.Default)
    }
    
    func cleanCache() {
        
        LDCacheManager.shareInstance.userCacheManger?.removeObjectForKey("ddplusinfo")
    }
    
    
    //
    func requestNet() {
        //
        LDCheckPublicInfo.shareInstance.queryWorthContent(true, succ: { [weak self] (value) in
            
            
            self?.oldData = value
            self?.updateUI(value)
            
            //            for dict in value {
            
            //                self?.model = LDWorthConfigureModel.yy_modelWithDictionary(dict as? [NSObject : AnyObject] ?? [NSObject : AnyObject]())
            //
            //
            //                self?.titleArr.append(self?.model?.title ?? "")
            //                self?.h5Arr.append(self?.model?.url ?? "")
            //
            //                let imgapi =  IPHONE6UP ? LDCommentAPI.getPicApi(self?.model?.img_url_3x ?? "") : LDCommentAPI.getPicApi(self?.model?.img_url_2x ?? "")
            //
            //                self?.imgNameUrlArr.append(imgapi)
            //                self?.contentView?.reloadData()
            
            //            }
        }) { (data) in
            
        }
    }
    
    func updateUI(value:NSArray) {
        
        titleArr.removeAll()
        imgNameUrlArr.removeAll()
        h5Arr.removeAll()
        
        
        for dict in value {
            model = LDWorthConfigureModel.yy_modelWithDictionary(dict as? [NSObject : AnyObject] ?? [NSObject : AnyObject]())
            
            titleArr.append(model?.title ?? "")
            h5Arr.append(model?.url ?? "")
            
            let imgapi =  IPHONE6UP ? LDCommentAPI.getPicApi(model?.img_url_3x ?? "") : LDCommentAPI.getPicApi(model?.img_url_2x ?? "")
            
            imgNameUrlArr.append(imgapi)
            contentView?.reloadData()
        }
        
    }
    
    //
    func setDefaultContent() {
        
        navigationController!.interactivePopGestureRecognizer!.enabled = true
        navigationController!.interactivePopGestureRecognizer!.delegate = nil
        
        headImgView = UIImageView(image: UIImage(named: "价值-海报"))
        let layout = LDWorthCollectionFlowLayout()
        layout.headerReferenceSize = CGSizeMake(LDFrame.ScreenWidth, headH)
        
        contentView = UICollectionView.init(frame: LDFrame.ScreenBounds, collectionViewLayout: layout)
        contentView?.alwaysBounceVertical = true
        contentView!.backgroundColor = LDGolbalColor.BgGoundGray
        contentView?.contentInset = UIEdgeInsetsMake(-64, 0, 40, 0)
        contentView?.translatesAutoresizingMaskIntoConstraints = true
        
        contentView?.delegate = self
        contentView?.dataSource = self
        
        view.addSubview(contentView!)
        
        contentView?.registerClass(LDFinderWorthCollectionCell.self, forCellWithReuseIdentifier: cellid)
        contentView?.registerClass(LDAddApplicationViewCell.self, forCellWithReuseIdentifier: tapcellid)
        
        contentView?.registerClass(LDFinderWorthHeadrView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headid)
        
        contentView?.registerClass(UIView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "footid")
    }
    
    
}

extension LDWorthVC:UICollectionViewDelegate,UICollectionViewDataSource {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return 2
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if section == 0 {
            
            if IPHONE6UP {
                
                if titleArr.count > 8 {
                    
                    return 12
                }
                
                return 8
            } else {
                
                if titleArr.count > 6 {
                    
                    return 9
                }
                return 6
            }
        } else {
            
            return 1
        }
        
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
//        let vc = LDBaseWebViewController()
//                let vc = RxWebViewController()
        let vc = DDDPlusBaseWKWebVC()
        
        if indexPath.section == 0 && indexPath.row < titleArr.count {
            
            let url = NSURL(string: h5Arr[indexPath.row])
            vc.url = h5Arr[indexPath.row]
//          vc.url = url
//          vc.reqUrl = h5Arr[indexPath.row]
            
            rdv_tabBarController.setTabBarHidden(true, animated: true)
        } else if indexPath.section == 1 {
            
            //暂时处理
//          vc.url = NSURL(string: "https://www.dingdong.cc/ddplus/appsmore/")
//          vc.reqUrl = "https://www.dingdong.cc/ddplus/appsmore/"
            vc.url = "https://www.dingdong.cc/ddplus/appsmore/"
            rdv_tabBarController.setTabBarHidden(true, animated: true)
        } else {
            return
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        if indexPath.section == 0 {
            
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellid, forIndexPath: indexPath) as! LDFinderWorthCollectionCell
            cell.iconName = ""
            if indexPath.row <= (titleArr.count - 1) {
                
                cell.title = titleArr[indexPath.row]
//              cell.imgView?.sd_setImageWithURL(NSURL(string: imgNameUrlArr[indexPath.row]))
                cell.iconName = imgNameUrlArr[indexPath.row]
            } else {
                cell.title = ""
            }
            
            return cell
            
        } else  { //if indexPath.section == 1
            
            let cell = collectionView.dequeueReusableCellWithReuseIdentifier(tapcellid, forIndexPath: indexPath) as! LDAddApplicationViewCell
            return cell
            
        }
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        
        if (kind == UICollectionElementKindSectionHeader) {
            
            let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headid, forIndexPath: indexPath) as? LDFinderWorthHeadrView
            
            if headImgView != nil {
                
                header?.imageView?.image = headImgView?.image
            }
            
            return header!
            
        } else {
            
            return UICollectionReusableView()
        }
    }
    
}

extension LDWorthVC:UICollectionViewDelegateFlowLayout {
    
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 0.5
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 0.5
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        
        return UIEdgeInsetsMake(0, 0, 0.5, 0)
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        
        if indexPath.section == 0 {
            
            if IPHONE6LOW {
                
                return CGSizeMake((LDFrame.ScreenWidth-CGFloat(0.5*2))/3, 100)
            } else {
                
                return CGSizeMake((LDFrame.ScreenWidth-CGFloat(0.5*3))/4, 100)
            }
        } else {
            
            return CGSizeMake(LDFrame.ScreenWidth, 80)
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        if section == 0 {
            
            return CGSizeMake(LDFrame.ScreenWidth, headH)
        } else {
            
            return CGSizeZero
        }
        
    }
}